package com.miaoji.mybatis.design._02;

import com.miaoji.mybatis.design._01.TestService;
import com.miaoji.mybatis.design._01.impl.TestServiceImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkProxy implements InvocationHandler {
    private Object targer;

    public JdkProxy(Object targer) {
        this.targer = targer;
    }

    public <T> T getProxy(Class<T> clz){
        //类加载器 增强所在的类  实现InvocationHandler接口，
        return (T) Proxy.newProxyInstance(clz.getClassLoader(),new Class[]{clz},this);
    }

    public static void main(String[] args) {
        JdkProxy jdkProxy= new JdkProxy(new TestServiceImpl());
        TestService proxy = jdkProxy.getProxy(TestService.class);
        System.out.println(proxy.selectList("xx"));
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("invoke before ...");
        Object invoke = method.invoke(this.targer, args);
        System.out.println("invoke after ...");
        return invoke;
    }
}
